<template>
  <div class="content-container">
    <!-- 添加空白区域，使内容向下移但不要太多 -->
    <div class="admin-page-spacer"></div>
    
    <el-card shadow="never" class="chat-container">
      <h1>DeepSeek 聊天助手</h1>
      <div id="chat-box" ref="chatBox" class="chat-messages">
        <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
          <div class="avatar-container" v-if="msg.role === 'assistant'">
            <div class="avatar">
              <img src="@/assets/deepseek.png" alt="DeepSeek Logo" />
            </div>
          </div>
          <div class="message-content">
            <div v-html="formatMarkdown(msg.content)" class="markdown-content"></div>
          </div>
        </div>
        <div v-if="isLoading" class="message assistant">
          <div class="avatar-container">
            <div class="avatar">
              <img src="@/assets/deepseek.png" alt="DeepSeek Logo" />
            </div>
          </div>
          <div class="loading-message">
            <img src="@/assets/loading.gif" alt="Loading..." class="loading-gif" />
          </div>
        </div>
      </div>
      <div class="chat-input-wrapper">
        <div class="chat-input">
          <el-input
              v-model="userInput"
              type="textarea"
              :autosize="{ minRows: 1, maxRows: 4 }"
              placeholder="输入您的消息..."
              @keyup.enter="sendMessage"
          />
          <el-button type="primary" @click="sendMessage" :loading="isLoading" circle>
            <el-icon><send /></el-icon>
            {{ isLoading ? '生成中...' : '发送' }}
          </el-button>
          <el-button type="danger" @click="clearChat" class="clear-chat-button">
            <el-icon><delete /></el-icon>
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import { chatAPI } from '@/api/admin/ai';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash-es';

// 定义用户输入
const userInput = ref('');
// 存储所有消息记录，每条消息包含角色和内容
const messages = ref([]);
// 加载状态
const isLoading = ref(false);
// 聊天框引用
const chatBox = ref(null);

// 创建 Markdown-it 实例
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: (str, lang) => {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${
            hljs.highlight(str, {
              language: lang,
              ignoreIllegals: true
            }).value
        }</code></pre>`;
      } catch (__) {}
    }
    return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`;
  }
});

// 函数：将 Markdown 格式文本转换为 HTML 字符串
const formatMarkdown = (text) => {
  return md.render(text);
};

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatBox.value) {
      chatBox.value.scrollTop = chatBox.value.scrollHeight;
    }
  });
};

// 发送消息的异步函数
const sendMessage = debounce(async () => {
  const message = userInput.value.trim();
  if (!message) return;

  // 将用户消息添加到聊天记录中
  messages.value.push({
    role: 'user',
    content: message,
  });
  userInput.value = '';
  scrollToBottom();

  isLoading.value = true;
  try {
    const data = await chatAPI.sendMessage(message);
    messages.value.push({
      role: 'assistant',
      content: data.response,
    });
    scrollToBottom();
  } catch (error) {
    ElMessage.error(`请求出错，请稍后再试: ${error.message}`);
  } finally {
    isLoading.value = false;
  }
}, 300);

// 清除聊天记录的函数
const clearChat = () => {
  messages.value = [];
};

onMounted(() => {
  window.addEventListener('resize', scrollToBottom);
  scrollToBottom();
});
</script>

<style scoped>
/* 容器优化 */
.content-container {
  margin-top: 15px;
}

.chat-container {
  width: 100%;
  height: 100vh; /* 使用视口全高 */
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  font-family: 'Arial', sans-serif;
  box-shadow: none;
  border: none;
  background-color: #fff;
}

.chat-container :deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px;
  margin-bottom: 80px; /* 给输入框留出空间 */
  scroll-behavior: smooth;
}

/* 消息气泡优化 */
.message {
  display: flex;
  margin-bottom: 20px;
  opacity: 0;
  transform: translateY(20px);
  animation: messageAppear 0.3s ease forwards;
  align-items: flex-start;
}

.message.assistant {
  justify-content: flex-start;
  margin-right: 15%;
}

.message.user {
  justify-content: flex-end;
  margin-left: 15%;
}

.avatar-container {
  margin-right: 12px;
  width: 50px;
  display: flex;
  justify-content: center;
}

.avatar {
  width: 36px;
  height: 36px;
  background-color: #f0f2f5;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.avatar img {
  width: 24px;
  height: 24px;
  object-fit: cover;
}

.message-content {
  max-width: calc(85% - 60px);
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.6;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 用户消息样式 */
.message.user .message-content {
  background: #409eff;
  color: white;
  border-radius: 12px 12px 0 12px;
}

/* AI 消息样式 */
.message.assistant .message-content {
  background: #f8f9fa;
  border: 1px solid #eee;
  border-radius: 12px 12px 12px 0;
}

/* Markdown 内容排版 */
.markdown-content {
  width: 100%;
}

/* 段落样式 */
.markdown-content :deep(p) {
  margin-bottom: 12px;
  text-align: justify;
  line-height: 1.7;
}

/* 标题样式 */
.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content :deep(h1) {
  font-size: 1.5em;
  border-bottom: none;
  padding-bottom: 0.3em;
}

.markdown-content :deep(h2) {
  font-size: 1.3em;
  border-bottom: none;
  padding-bottom: 0.3em;
  margin-top: 24px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.markdown-content :deep(h2)::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 1em;
  background-color: #333;
  margin-right: 8px;
}

.markdown-content :deep(h3) {
  font-size: 1.1em;
}

/* 列表样式 */
.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  padding-left: 1.5em;
  margin-bottom: 16px;
}

.markdown-content :deep(li) {
  margin-bottom: 4px;
  line-height: 1.7;
  position: relative;
}

.markdown-content :deep(li)::marker {
  color: #666;
}

.markdown-content :deep(li + li) {
  margin-top: 0.25em;
}

/* 嵌套列表项 */
.markdown-content :deep(li > ul),
.markdown-content :deep(li > ol) {
  margin-top: 4px;
  margin-bottom: 0;
}

/* 列表符号 */
.markdown-content :deep(ul) {
  list-style-type: disc;
}

.markdown-content :deep(ul ul) {
  list-style-type: circle;
}

.markdown-content :deep(ul ul ul) {
  list-style-type: square;
}

/* 引用块 */
.markdown-content :deep(blockquote) {
  border-left: 4px solid #ddd;
  color: #666;
  padding: 0 1em;
  margin: 0 0 16px 0;
}

.markdown-content :deep(blockquote > :first-child) {
  margin-top: 0;
}

.markdown-content :deep(blockquote > :last-child) {
  margin-bottom: 0;
}

/* 水平线 */
.markdown-content :deep(hr) {
  height: 1px;
  padding: 0;
  margin: 24px 0;
  background-color: #e1e4e8;
  border: 0;
  position: relative;
  width: 100%;
}

/* 项目符号前缀 */
.markdown-content :deep(ul li)::before {
  content: "";
  position: absolute;
  left: -1.2em;
  top: 0.6em;
}

/* 加载消息样式 */
.loading-message {
  display: flex;
  align-items: center;
  background: #f0f2f5;
  padding: 8px 16px;
  border-radius: 18px;
}

.loading-gif {
  height: 24px;
  width: auto;
}

/* 代码块专用样式 */
.markdown-content :deep(pre) {
  background: #1a1a1a !important;
  border-radius: 8px;
  padding: 16px !important;
  margin: 12px 0;
  border: 1px solid #333;
  overflow-x: auto;
}

.markdown-content :deep(code) {
  font-family: 'Menlo', 'Consolas', monospace !important;
  font-size: 14px;
  color: #c9d1d9;
}

/* 输入框容器 */
.chat-input-wrapper {
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center; /* 水平居中 */
  width: 100%;
  z-index: 10;
}

/* 输入框区域优化 */
.chat-input {
  width: 80%; /* 控制输入框宽度，可以根据需要调整 */
  max-width: 800px;
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  display: flex;
  gap: 12px;
  align-items: center;
}

.el-input {
  flex: 1;
}

.el-button {
  height: 40px;
  padding: 0 24px;
  border-radius: 4px;
}

@keyframes messageAppear {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-container h1 {
  text-align: center;
  margin-bottom: 20px;
}

.chat-container h1,
.chat-container h2,
.chat-container h3 {
  font-weight: bold;
  margin-top: 16px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .chat-input {
    width: 90%;
    padding: 12px;
  }

  .message-content {
    max-width: calc(90% - 60px);
  }

  .el-button {
    padding: 0 15px;
  }

  .avatar {
    width: 32px;
    height: 32px;
  }
}

/* 清除聊天记录按钮样式 */
.clear-chat-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
</style>